package com.util;

import java.io.Serializable;
import java.util.List;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;


public class KeyGenerate implements Configurable,IdentifierGenerator{
	private String sign;
	private String className;
	private String pk;
	private String idLength;

	@Override
	public Serializable generate(SessionImplementor sessionimplementor,
			Object obj) throws HibernateException {
		int leng = Integer.parseInt(idLength);
		StringBuffer sql = new StringBuffer("select max(a.").append(pk).append(") from ")
				.append(className).append(" as a where a.").append(pk).append(" like '")
				.append(sign).append("%'");
		QueryParameters qp = new QueryParameters();
		@SuppressWarnings("unchecked")
		List<String> list = sessionimplementor.list(sql.toString(),qp);
		String max = list.get(0);
		int i = 0;
		
		if(max == null || "".equals(max.trim())){
			max = "1";
			for (; i < leng - sign.length() - 1; i++) {
				max = "0" + max;
			}
			i = 0;
			return sign + max;
		}
		else if (max != null && max.length() <= leng) {
			max = max.replaceAll(sign, "");
			Integer imax = Integer.parseInt(max) + 1;
			String returnnum = String.valueOf(imax);
			int zero = leng-sign.length()-returnnum.length();
			for(; i < zero; i++) {
				returnnum = "0" + returnnum;
			}
			i = 0;
			 return sign + returnnum;
		}
		else {
			leng = max.length();
			max = max.replaceAll(sign, "");
			Integer imax = Integer.parseInt(max) + 1;
			String returnnum = String.valueOf(imax);
			int zero = leng-sign.length()-returnnum.length();
			for(; i < zero; i++) {
				returnnum = "0" + returnnum;
			}
			i = 0;
			 return sign + returnnum;
		}		
	}

	@Override
	public void configure(Type type, Properties properties,
			ServiceRegistry serviceregistry) throws MappingException {
		this.sign = properties.getProperty("sign");
		this.className = properties.getProperty("className");
		this.pk = properties.getProperty("pk");
		this.idLength = properties.getProperty("idLength");
	}

}
